package com.signway.module_signway_adapter_Api;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.signwaymanager.SignwayManager;
import android.util.Log;

import com.signway.open.api.IOpenNetworkApi;
import com.signway.open.api.constant.SettingConstant;
import com.signway.utils.LogHelper;
import com.signway.utils.SystemPropertiesInvoke;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2011-2019, by your Signway, All rights reserved.
 * -----------------------------------------------------------------
 *
 * ProjectName: droid5119
 *
 * Author: Administrator
 *
 * Email: pf.wang@Signway.cn
 *
 * Description:网络相关设置接口
 *
 * -----------------------------------------------------------------
 * 2019-5-30 : Create SignwayNetworkApi.java
 * -----------------------------------------------------------------
 */
public class SignwayNetworkApi implements IOpenNetworkApi {

    private static final String TAG = "960NetworkApi";
    private static SignwayNetworkApi mSignwayNetworkApi;
    private static Context mContext;
    private SignwayManager mSignwayManager;

    public static synchronized SignwayNetworkApi getInstance(Context context) {
        mContext = context;
        if (mSignwayNetworkApi == null) {
            mSignwayNetworkApi = new SignwayNetworkApi(context);
        }
        return mSignwayNetworkApi;
    }

    public SignwayNetworkApi(Context context) {
        this.mContext = context;
        mSignwayManager = SignwayManager.getInstance(mContext);
    }
    /**
     * 以太网开关
     *
     * @param isOpen true:开 false:关
     */
    public void setEthernet(boolean isOpen) {
        LogHelper.d("setEthernet isOpen is " + isOpen);
        mSignwayManager.setEthernetEnabled(isOpen);
    }

    /**
     * wifi开关
     *
     * @param isOpen true:开 false:关
     */
    public void setWifi(boolean isOpen) {
        LogHelper.d("setWifi isOpen is " + isOpen);
        if (isOpen) {
            mSignwayManager.setWifiEnabled(true);
//            WifiControl.getInstance().init();
        } else {
            mSignwayManager.setWifiEnabled(false);
//            WifiControl.getInstance().destroy();
        }
    }

    /**
     * 手机移动网络开关
     *
     * @param isOpen true:开 false:关
     */
    public void setMobile(boolean isOpen) {
        LogHelper.d("setMobile isOpen is " + isOpen);
        mSignwayManager.setMobileEnabled(isOpen);
    }

    /**
     * 获取mac地址
     *
     * @return
     */
    public String getMac(int boardType) {
        String mac = null;
        if (boardType == 2) {
            return mac;
        } else {
            if (getSysMac() != null) {
                return getSysMac();
            }
        }
        return "0C-63-FC-00-00-01";
    }

    public String getSysMac() {
        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/eth0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException e) {
            // 取默认值
            e.printStackTrace();
        }
        return macSerial;
    }


    /**
     * 获取静态地址IP
     *
     * @return
     */
    String tempDhcpIPinfo;
    public String getDhcpIp() {
        String iface = "eth0";
        String dhcpIP = "0.0.0.0"; // dhcp ip
//        String tempIpInfo = SignwayApi.systemAPI().getSystemProperties("dhcp." + iface + ".ipaddress");
        tempDhcpIPinfo = mSignwayManager.getEthIpAddress();
        Log.d(TAG,"tempDhcpIPinfo-->" + tempDhcpIPinfo);
        if ((tempDhcpIPinfo != null) && (!tempDhcpIPinfo.equals(""))) {
            dhcpIP = tempDhcpIPinfo;
        } else {
            dhcpIP = "0.0.0.0";
        }
        return dhcpIP;
    }

    /**
     * 获取静态地址掩码
     *
     * @return
     */
    String tempDhcpMask = "0.0.0.0";
    public String getDhcpMask() {
        String iface = "eth0";
        String dhcpMask = "0.0.0.0"; // dhcpMask
        String tempIpInfo = SystemPropertiesInvoke.get("dhcp." + iface + ".mask",dhcpMask);
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
            dhcpMask = tempIpInfo;
        } else {
            dhcpMask = "0.0.0.0";
        }
        LogHelper.d("DHCPMask-->" + dhcpMask);
        return dhcpMask;
    }

    /**
     * 获取静态地址网关
     *
     * @return
     */
    String dhcpGateway = "0.0.0.0"; // dhcpGateway
    public String getDhcpGetway() {
        String iface = "eth0";
//        String tempIpInfo = SignwayApi.systemAPI().getSystemProperties("dhcp." + iface + ".gateway");
        String tempIpInfo = SystemPropertiesInvoke.get("dhcp." + iface + ".gateway",dhcpGateway);
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
            dhcpGateway = tempIpInfo;
        } else {
            dhcpGateway = "0.0.0.0";
        }
        return dhcpGateway;
    }

    /**
     * 获取静态地址域名1
     *
     * @return
     */
    public String getDhcpDns1() {
        String iface = "eth0";
        String dhcpDNS = "0.0.0.0"; // dhcpDNS
//        String tempIpInfo = SignwayApi.systemAPI().getSystemProperties("dhcp." + iface + ".dns1");
        String tempIpInfo = SystemPropertiesInvoke.get("dhcp." + iface + ".dns1",dhcpDNS);
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
            dhcpDNS = tempIpInfo;
        } else {
            dhcpDNS = "0.0.0.0";
        }
        return dhcpDNS;
    }

    /**
     * 获取网络地址掩码
     *
     * @return
     */
    public String getNetworkMask(Context context,int workMode) {
        String mask = "255.255.255.255";
        int work_mode = workMode;
        switch (work_mode) {
            case SettingConstant.SINGLE: {
                String networkName = getNetworkName(context);
                if ("WIFI".equals(networkName)) {
                    mask = mSignwayManager.getNetMask("WIFI");
                } else if ("Ethernet".equals(networkName)) {
                    mask = mSignwayManager.getNetMask("ETHERNET");
//                    if (isNetworkAuto) {
//                        mask = mSignwayManager.getNetMask("ETHERNET");
//                    } else {
//                        mask = SettingArmData.getNetworkMask();
//                    }
                }
            }
            break;
            case SettingConstant.NETWORK:
//                if (SettingArmData.isNetworkAuto()) {
//                    mask = mSignwayManager.getNetMask("ETHERNET");
//                } else {
//                    mask = SettingArmData.getNetworkMask();
//                }
                mask = mSignwayManager.getNetMask("ETHERNET");
                break;
            case SettingConstant.WIFI:
                mask = mSignwayManager.getNetMask("WIFI");
                break;
            case SettingConstant.MOBILE:
                break;
            default:
                break;
        }
        return mask;
    }

    //获取当前网络名称   wifi  以太网
    public String getNetworkName(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
        // 遍历每一个对象
        for (NetworkInfo networkInfo : networkInfos) {
            if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                // 网络状态可用
                return networkInfo.getTypeName();
            }
        }
        // 没有可用的网络
        return "";
    }

    /**
     * 设置以太网静态IP
     *
     * @return
     */
    public boolean setStaticIpConfiguration(String localIP,String localMask,String localGateway,String localDNS,String localDNS1) {
        Log.i("CurrentNetType","网络类型："+"IP_STATIC"+"--localMask："+localMask+"--以太网静态IP："+localIP
                +"--localGateway："+localGateway+"---localDNS:"+localDNS + "---localDNS1:" + localDNS1);

        mSignwayManager.setStaticEthIPAddress(localIP, localGateway, localMask, localDNS, localDNS1);

        mSignwayManager.setEthMode("Staticip");

        return true;
    }

    /**
     * 设置DHCP
     */
    public void setDhcpIpConfiguration() {
        mSignwayManager.setEthMode("DHCP");

    }

    /**
     * 获取以太网连接状态
     * @return
     */
    public int getEthernetConnectStatus() {
        int NETWORK_STATE_DISCONNECT = 0;
        int NETWORK_STATE_CONNECT = 1;
        int status = mSignwayManager.getCurrentNetType();  //返回100，则表示当前无网络连接；0-->以太网；1-->WIFI；2-->2G网络；3-->3G或3G以上的网络
        if (status == 100) {
            return NETWORK_STATE_DISCONNECT;
        } else {
            return NETWORK_STATE_CONNECT;
        }
    }

    /*
     * 打开网络 mode：NETWORK_ETHERNET、NETWORK_WIFI、NETWORK_3G
     */
    public void openNetworkMode(int mode,boolean isMobileOpen) {
        if (mode == SettingConstant.WIFI) {
            setMobile(false);
            setEthernet(false);
            setWifi(true);
        } else if (mode == SettingConstant.NETWORK) {
            setMobile(false);
            setEthernet(true);
            setWifi(false);
        } else if (mode == SettingConstant.SINGLE) {
            setMobile(false);
            setEthernet(false);
            setWifi(false);
        } else if (mode == SettingConstant.MOBILE) {
            if (isMobileOpen/*SettingArmData.getMobileSwitch()*/) {
                setMobile(true);
            } else {
                setMobile(false);
            }
            setEthernet(false);
            setWifi(false);
        }
    }

    @Override
    public void initWifi(int workMode) {
        boolean wifiEnabled = SignwayManager.getInstance(mContext).isWifiEnabled();
        LogHelper.d(TAG,"initWifi====" + workMode + "  " + wifiEnabled);
        if (workMode == SettingConstant.WIFI) {
            if (!wifiEnabled) {
                mSignwayManager.setWifiEnabled(true);
            }
        } else {
            if (wifiEnabled) {
                mSignwayManager.setWifiEnabled(false);
            }
        }
    }

    @Override
    public boolean isLocalConnected(int workMode) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        int networkType = -1;
        switch (workMode) {
            case SettingConstant.NETWORK:
                networkType = ConnectivityManager.TYPE_ETHERNET;
                break;
            case SettingConstant.WIFI:
                networkType = ConnectivityManager.TYPE_WIFI;
                break;
            case SettingConstant.MOBILE:
                networkType = ConnectivityManager.TYPE_MOBILE;
                break;
        }

        if (networkType == -1) {
            return false;
        }

        NetworkInfo info = connectivityManager.getNetworkInfo(networkType);
        String hostAddress = getLocalIpv4Address();
//        SettingArmData.setConf_local_ip(hostAddress);
        LogHelper.w("hostAddress:" + hostAddress);
        LogHelper.w("inf:" + info.toString());
        LogHelper.w("EthernetConnectStatus:" + getEthernetConnectStatus());

        int connect = mSignwayManager.getCurrentNetType();
        if (connect == 100){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 检测机器是否设置了接入点
     *
     * @return
     */
    public int getWifiState() {
        WifiManager mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        if (mWifiManager.isWifiEnabled()) {
            int state = mWifiManager.getWifiState();
            if (state == WifiManager.WIFI_STATE_DISABLED
                    || state == WifiManager.WIFI_STATE_DISABLING
                    || state == WifiManager.WIFI_STATE_UNKNOWN) {
                LogHelper.i("wifi state = " + state);
                return 2;  //wifi无效
            } else {
                WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
                if (null == mWifiInfo) {
                    return 3;  //wifi连接失败
                } else {
                    String ssid = mWifiInfo.getSSID();
                    LogHelper.d("ssid:" + ssid);
                    if (null != ssid && !"0x".equals(ssid)) {
                        return 0;
                    } else {
                        return 4;  //wifi SSID不对
                    }
                }
            }
        } else {
            return 1;  //wifi不可用
        }
    }

    /**
     * 移动网络修复
     */
    public void repairMobile() {
//        GpioOper.getInstance().repairMobile();
        mSignwayManager.set4GModuleReset();
    }


    public static String getLocalIpv4Address() {
        try {
            if (NetworkInterface.getNetworkInterfaces() != null) {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                    if (en != null) {

                        NetworkInterface intf = en.nextElement();

                        if (intf == null) {
                            continue;
                        }
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                .hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            LogHelper.d("WifiPreference IpAddress---error-" + e.toString());
        } catch (Exception e) {
            LogHelper.d("WifiPreference IpAddress---error2-" + e.toString());
        }
        return null;
    }


}
